//
//  DHS2_PreOrderController.m
//  Dresshere
//
//  Created by ZhangPeng on 2018/6/10.
//  Copyright © 2018年 张朋. All rights reserved.
//

#import "DHS2_PreOrderController.h"
#import "DHS2_PreOrder_AddressCell.h"
#import "DHS2_PreOrder_ItemCell.h"
#import "DHS2_PreOrder_CouponsCell.h"
#import "DHS2_PreOrder_WashingCell.h"
#import "DHS2_PreOrder_PriceCell.h"
#import "DHContactViewController.h"
#import "DHMyCouponsController.h"
#import "Address.h"
#import "DHPayViewController.h"
#import "DHS2_OrderDetailController.h"

@interface DHS2_PreOrderController ()<UITableViewDelegate, UITableViewDataSource>

@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (weak, nonatomic) IBOutlet UILabel *priceLabel;
@property (strong, nonatomic) NSArray *addressArr;

@property (weak, nonatomic) IBOutlet UIButton *payButton;
@property (strong, nonatomic) Address *address;
@property (strong, nonatomic) Address *returnAddress;
@property (assign, nonatomic) BOOL isSix; //是否是6小时送达城市

@property (strong, nonatomic) NSMutableDictionary *orderDetailDic;
@property (assign, nonatomic) NSInteger couponCounts;

@property (assign, nonatomic) CGFloat totalPrice;

@end

@implementation DHS2_PreOrderController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.titleLabel.text = @"订单预览";
    
    self.couponCounts = 0;
    
    [self.tableView registerNib:[UINib nibWithNibName:@"DHS2_PreOrder_AddressCell" bundle:nil] forCellReuseIdentifier:kDHS2_PreOrder_AddressCell];
    [self.tableView registerNib:[UINib nibWithNibName:@"DHS2_PreOrder_ItemCell" bundle:nil] forCellReuseIdentifier:kDHS2_PreOrder_ItemCell];
    [self.tableView registerNib:[UINib nibWithNibName:@"DHS2_PreOrder_CouponsCell" bundle:nil] forCellReuseIdentifier:kDHS2_PreOrder_CouponsCell];
    [self.tableView registerNib:[UINib nibWithNibName:@"DHS2_PreOrder_WashingCell" bundle:nil] forCellReuseIdentifier:kDHS2_PreOrder_WashingCell];
    [self.tableView registerNib:[UINib nibWithNibName:@"DHS2_PreOrder_PriceCell" bundle:nil] forCellReuseIdentifier:kDHS2_PreOrder_PriceCell];
    
    [self loadOrderDetail];
    
    addNObserver(@selector(changeAddress:), @"DHContactViewController");
    addNObserver(@selector(returnAddress:), @"return_address");
    
    NSData *addressData = [[NSUserDefaults standardUserDefaults] objectForKey:USER_ORDER_BUY_ADDRESS];
    self.address = [NSKeyedUnarchiver unarchiveObjectWithData:addressData];
    
    //使用优惠券
    addNObserver(@selector(use_coupon), @"use_coupon");
}

- (void)dealloc{
    removeNObserver(@"DHContactViewController");
    removeNObserver(@"return_address");
    removeNObserver(@"use_coupon");
}

- (void)use_coupon{
    [[DHNetAPIClient shareDHNetAPIClient] request_orders_detailWithParams:@{@"order_id":self.orderId} andBlock:^(id data, NSError *error) {
        if (data) {
            self.orderDetailDic = [data objectForKey:@"order"];
            [self.tableView reloadRow:3 inSection:0 withRowAnimation:UITableViewRowAnimationNone];
            [self loadCouponCounts];
            [self.tableView reloadRow:4 inSection:0 withRowAnimation:UITableViewRowAnimationNone];
            [self loadCouponCounts];
            
            self.totalPrice = 0;
            NSArray *costArray = [self.orderDetailDic objectForKey:@"cost"];
            for (NSDictionary *dic in costArray) {
                CGFloat value = [[dic objectForKey:@"value"] floatValue];
                self.totalPrice += value;
            }
            self.priceLabel.text = [NSString stringWithFormat:@"合计：￥%.2f",self.totalPrice];
            if (self.totalPrice == 0) {
                [self.payButton setTitle:@"确认订单" forState:UIControlStateNormal];
            }else{
                [self.payButton setTitle:@"支付" forState:UIControlStateNormal];
            }
        }
    }];
}

// 去结算
- (IBAction)goSettlementAction:(id)sender {
    [[DHNetAPIClient shareDHNetAPIClient] request_order_confirmWithParams:@{@"order_id":[self.orderDetailDic objectForKey:@"_id"]} andBlock:^(id data, NSError *error) {
        if (data) {
            NSDictionary *order = [data objectForKey:@"order"];
            if ([self.payButton.titleLabel.text isEqualToString:@"确认订单"]) {
                // 订单详情
                DHS2_OrderDetailController *vc = [[DHS2_OrderDetailController alloc] init];
                vc.order_id = [order objectForKey:@"_id"];
                [self.navigationController pushViewController:vc animated:YES];
            }else{
                NSArray *cost = [order objectForKey:@"cost"];
                __block CGFloat price = 0;
                [cost enumerateObjectsUsingBlock:^(NSDictionary *obj, NSUInteger idx, BOOL * _Nonnull stop) {
                    CGFloat value = [[obj objectForKey:@"value"] floatValue];
                    price += value;
                }];
                DHPayViewController *vc = [[DHPayViewController alloc] initWithPrice:@(price) order_id:[order objectForKey:@"_id"]];
                vc.payType = PayTypeOrder;
                [self.navigationController pushViewController:vc animated:YES];
            }
        }
    }];
}

- (void)changeAddress:(NSNotification *)not{
    if (not){
        NSDictionary *dic = not.object;
        self.address = [dic objectForKey:@"address"];
        self.isSix = [[GlobalManager shareGlobalManager].supportCitiesArray containsObject:self.address.city];
        NSDictionary *params = @{@"order_id":self.orderId,
                                 @"contact":self.address.name,
                                 @"province":self.address.province,
                                 @"city":self.address.city,
                                 @"district":self.address.district,
                                 @"address":self.address.address,
                                 @"accurate":self.address.accurate,
                                 @"phone":self.address.phone,
                                 };
        [[DHNetAPIClient shareDHNetAPIClient] request_order_receiverWithParams:params andBlock:^(id data, NSError *error) {
            NSData *addressData = [NSKeyedArchiver archivedDataWithRootObject:self.address];
            [[NSUserDefaults standardUserDefaults] setObject:addressData forKey:USER_ORDER_BUY_ADDRESS];
            [[NSUserDefaults standardUserDefaults] synchronize];
            [self loadOrderDetail];
        }];
        
        if ([[self.orderDetailDic objectForKey:@"washing"] count] > 0) {
            [[DHNetAPIClient shareDHNetAPIClient] request_order_washing_returnWithParams:params andBlock:^(id data, NSError *error) {
                [self loadOrderDetail];
            }];
        }
    }
}

- (void)returnAddress:(NSNotification *)not{
    if (not){
        NSDictionary *dic = not.object;
        self.returnAddress = [dic objectForKey:@"address"];
//        self.isSix = [[GlobalManager shareGlobalManager].supportCitiesArray containsObject:self.address.city];
        NSDictionary *params = @{@"order_id":self.orderId,
                                 @"contact":self.returnAddress.name,
                                 @"province":self.returnAddress.province,
                                 @"city":self.returnAddress.city,
                                 @"district":self.returnAddress.district,
                                 @"address":self.returnAddress.address,
                                 @"accurate":self.returnAddress.accurate,
                                 @"phone":self.returnAddress.phone,
                                 };
        [[DHNetAPIClient shareDHNetAPIClient] request_order_washing_returnWithParams:params andBlock:^(id data, NSError *error) {
            NSData *addressData = [NSKeyedArchiver archivedDataWithRootObject:self.address];
            [[NSUserDefaults standardUserDefaults] setObject:addressData forKey:USER_ORDER_BUY_ADDRESS];
            [[NSUserDefaults standardUserDefaults] synchronize];
            [self loadOrderDetail];
        }];
        
        [[DHNetAPIClient shareDHNetAPIClient] request_order_receiverWithParams:params andBlock:^(id data, NSError *error) {
            [self loadOrderDetail];
        }];
    }
}

// 获取订单详情
- (void)loadOrderDetail{
    [[DHNetAPIClient shareDHNetAPIClient] request_orders_detailWithParams:@{@"order_id":self.orderId} andBlock:^(id data, NSError *error) {
        if (data) {
            self.orderDetailDic = [data objectForKey:@"order"];
            if (![[self.orderDetailDic objectForKey:@"receiver"] objectForKey:@"phone"]) {
                if (self.address) {
                    self.isSix = [[GlobalManager shareGlobalManager].supportCitiesArray containsObject:self.address.city];
                    NSDictionary *params = @{@"order_id":self.orderId,
                                             @"contact":self.address.name,
                                             @"province":self.address.province,
                                             @"city":self.address.city,
                                             @"district":self.address.district,
                                             @"address":self.address.address,
                                             @"accurate":self.address.accurate,
                                             @"phone":self.address.phone,
                                             };
                    [[DHNetAPIClient shareDHNetAPIClient] request_order_receiverWithParams:params andBlock:^(id data, NSError *error) {
                        [self loadOrderDetail];
                    }];
                    if ([[self.orderDetailDic objectForKey:@"washing"] count] > 0) {
                        [[DHNetAPIClient shareDHNetAPIClient] request_order_washing_returnWithParams:params andBlock:^(id data, NSError *error) {
                            [self loadOrderDetail];
                        }];
                    }
                }else{
                    [self.tableView reloadData];
                }
            }else{
                [self.tableView reloadData];
            }
            
            self.totalPrice = 0;
            NSArray *costArray = [self.orderDetailDic objectForKey:@"cost"];
            for (NSDictionary *dic in costArray) {
                CGFloat value = [[dic objectForKey:@"value"] floatValue];
                self.totalPrice += value;
            }
            self.priceLabel.text = [NSString stringWithFormat:@"合计：￥%.2f",self.totalPrice];
            if (self.totalPrice == 0) {
                [self.payButton setTitle:@"确认订单" forState:UIControlStateNormal];
            }else{
                [self.payButton setTitle:@"支付" forState:UIControlStateNormal];
            }
            [self loadCouponCounts];
        }
    }];
}

// 获取可用优惠券数量
- (void)loadCouponCounts{
    [[DHNetAPIClient shareDHNetAPIClient] request_coupons_valid_countWithParams:@{@"type":@"现金券",@"amount":@(self.totalPrice)} andBlock:^(id data, NSError *error) {
        self.couponCounts = [[data objectForKey:@"count"] integerValue];
        [self.tableView reloadRow:3 inSection:0 withRowAnimation:UITableViewRowAnimationNone];
    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - UITableViewDelegate and UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 5;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.row == 0) {
        return 135;
    }else if (indexPath.row == 1){
        NSArray *leasedArr = [self.orderDetailDic objectForKey:@"subscribed"];
        NSArray *purchasedArr = [self.orderDetailDic objectForKey:@"purchased"];
        NSInteger row;
        if (leasedArr.count > 0 && purchasedArr.count > 0) {
            row = 2;
        }else{
            row = 1;
        }
        CGFloat cityHeight = 0;
        NSDictionary *receiver = [self.orderDetailDic objectForKey:@"receiver"];
        if ([receiver objectForKey:@"phone"]) {
            if ([[GlobalManager shareGlobalManager].supportCitiesArray containsObject:[receiver objectForKey:@"city"]]) {
                cityHeight = 70;
            }
        }
        return 46 * row + leasedArr.count * 100 + purchasedArr.count * 100 + 10 + cityHeight;
    }else if (indexPath.row == 2){
        NSArray *washingArr = [self.orderDetailDic objectForKey:@"washing"];
        if (washingArr.count > 0) {
            return 135 + 40 * washingArr.count;
        }else{
            return 0;
        }
    }else if (indexPath.row == 3){
        if (self.couponCounts > 0 || [[self.orderDetailDic objectForKey:@"coupons"]  count] > 0) {
            return 85;
        }else{
            return 0;
        }
    }else if (indexPath.row == 4){
        NSArray *costArray = [self.orderDetailDic objectForKey:@"cost"];
        return 41 + 30 * costArray.count + 5;
    }else{
        return 100;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.row == 0) {
        DHS2_PreOrder_AddressCell *cell = [tableView dequeueReusableCellWithIdentifier:kDHS2_PreOrder_AddressCell forIndexPath:indexPath];
        [cell updateCell:[self.orderDetailDic objectForKey:@"receiver"]];
        return cell;
    }else if (indexPath.row == 1){
        DHS2_PreOrder_ItemCell *cell = [tableView dequeueReusableCellWithIdentifier:kDHS2_PreOrder_ItemCell forIndexPath:indexPath];
        [cell updateCell:self.orderDetailDic];
        return cell;
    }else if (indexPath.row == 2){
        DHS2_PreOrder_WashingCell *cell = [tableView dequeueReusableCellWithIdentifier:kDHS2_PreOrder_WashingCell forIndexPath:indexPath];
        [cell updateCell:self.orderDetailDic];
        NSArray *washingArr = [self.orderDetailDic objectForKey:@"washing"];
        if (washingArr.count == 0) {
            cell.contentView.hidden = YES;
        }else{
            cell.contentView.hidden = NO;
        }
        return cell;
    }else if (indexPath.row == 3){
        DHS2_PreOrder_CouponsCell *cell = [tableView dequeueReusableCellWithIdentifier:kDHS2_PreOrder_CouponsCell forIndexPath:indexPath];
        [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
        cell.countLabel.text = [NSString stringWithFormat:@"%ld张",(long)self.couponCounts];
        NSArray *couponArr = [self.orderDetailDic objectForKey:@"coupons"];
        if (couponArr.count > 0) {
            NSDictionary *dic = couponArr[0];
            cell.priceLabel.text = [NSString stringWithFormat:@"-￥%.1f",[[dic objectForKey:@"discount"] floatValue]];
        }
        if (self.couponCounts == 0) {
            cell.contentView.hidden = YES;
        }else{
            cell.contentView.hidden = NO;
        }
        return cell;
    }else if (indexPath.row == 4){
        DHS2_PreOrder_PriceCell *cell = [tableView dequeueReusableCellWithIdentifier:kDHS2_PreOrder_PriceCell forIndexPath:indexPath];
        [cell updateCell:self.orderDetailDic];
        return cell;
    }
    else{
        return nil;
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.row == 0) {
        DHContactViewController *addressController = [[DHContactViewController alloc] init];
        addressController.address = self.address;
        [self.navigationController pushViewController:addressController animated:YES];
    }else if (indexPath.row == 3){
        DHMyCouponsController *vc = [[DHMyCouponsController alloc] init];
        vc.isOrder = YES;
        vc.orderPrice = self.totalPrice;
        vc.order_id = [self.orderDetailDic objectForKey:@"_id"];
        [self.navigationController pushViewController:vc animated:YES];
    }
}

#pragma mark - arr
- (NSArray *)addressArr{
    if (!_addressArr) {
        _addressArr = [NSArray array];
    }
    return _addressArr;
}

@end
